import { useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { fetchFoodsList, addCart, incrementCart, decrementCart, clearCart } from './store/modules/takeaway'
import './index.css'

function ReduxShopping() {
	const { foodsList, cartList } = useSelector((state) => state.takeaway) // 从 Redux store 中获取数据
	const dispatch = useDispatch()

	// 已选商品 count 之和总数量
	const totalCount = cartList.reduce((acc, cur) => acc + cur.count, 0)
	// 已选商品总价
	const totalPrice = cartList.reduce((acc, cur) => acc + cur.price * cur.count, 0)

	useEffect(() => {
		dispatch(fetchFoodsList()) // 调用异步 action
	}, [dispatch])

	return (
		<>
			<h2>Redux购物案例</h2>
			<hr />

			{/* 商品列表 */}
			<h4>技术栈商品列表：</h4>
			<ul>
				{foodsList.map((food) => (
					<li style={{ margin: '10px' }} key={food.id}>
						{food.name} - ￥{food.price}
						&nbsp; &nbsp;
						<button onClick={() => dispatch(addCart(food))}>加入购物车</button>
					</li>
				))}
			</ul>

			{/* 购物车商品列表 */}
			<h4 className={`${cartList.length > 0 && 'has'}`}>
				购物车商品(已选{totalCount}个) = 总价：￥{totalPrice.toFixed(2)}
				&nbsp;
				<button onClick={() => dispatch(clearCart())}>清除购物车</button>
			</h4>
			<ul>
				{cartList.map((item) => (
					<li style={{ margin: '10px' }} key={item.id}>
						{item.name} - ￥{item.price} - 已选数量：{item.count}
						&nbsp;
						<button onClick={() => dispatch(incrementCart(item))}>+1</button>
						&nbsp;
						<button onClick={() => dispatch(decrementCart(item))}>-1</button>
					</li>
				))}
			</ul>
		</>
	)
}

export default ReduxShopping
